package com.cotasul.tela.autorizacao;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

import com.cotasul.bean.UsuarioBean;

public class AutorizaSessao implements PhaseListener {

	private static final long serialVersionUID = 5877802795737727089L;

	@Override
	public void afterPhase(PhaseEvent event) {
		FacesContext facesContext = event.getFacesContext();
		String currentPage = facesContext.getViewRoot().getViewId();

		boolean isLoginPage = (currentPage.lastIndexOf("/index.xhtml") > -1);
		HttpSession session = (HttpSession) facesContext.getExternalContext()
				.getSession(true);
		UsuarioBean usuario = (UsuarioBean) session.getAttribute("usuario");

		if (!isLoginPage && (usuario == null || usuario.getCodigo() == null)) {
			NavigationHandler nh = facesContext.getApplication()
					.getNavigationHandler();
			nh.handleNavigation(facesContext, null, "/index.xhtml");
		}
	}

	@Override
	public void beforePhase(PhaseEvent event) {
		
/*		FacesContext context = event.getFacesContext();
		ExternalContext ext = context.getExternalContext();
		HttpSession session = (HttpSession) ext.getSession(false);
		boolean newSession = (session == null) || (session.isNew());
		boolean postback = !ext.getRequestParameterMap().isEmpty();
		boolean timedout = postback && newSession;
		if (timedout) {
			Application app = context.getApplication();
			ViewHandler viewHandler = app.getViewHandler();
			UIViewRoot view = viewHandler.createView(context, homepage);
			context.setViewRoot(view);
			context.renderResponse();
			try {
				viewHandler.renderView(context, view);
				context.responseComplete();
			} catch (Throwable t) {
				throw new FacesException("Session timed out", t);
			}
		}
		*/
		
	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}

}
